import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bsbdj/bean/user_info.dart';
import 'package:flutter_bsbdj/bmob/bmob/bmob_query.dart';
import 'package:flutter_bsbdj/interfaces/view_interface.dart';
import 'package:flutter_bsbdj/pagers/ebook/novel.dart';
import 'package:flutter_bsbdj/pagers/episodes/episode.dart';
import 'package:flutter_bsbdj/pagers/mei_tu.dart';
import 'package:flutter_bsbdj/pagers/music/music_index.dart';
import 'package:flutter_bsbdj/pagers/news/news_index.dart';
import 'package:flutter_bsbdj/pagers/today_vidwo.dart';
import 'package:flutter_bsbdj/pagers/music/music_suspension_window.dart';
import 'package:flutter_bsbdj/pagers/user/login.dart';
import 'package:flutter_bsbdj/utils/shared_preferences_util.dart';
import 'package:flutter_bsbdj/utils/widget_views.dart';
import '../utils/constant.dart';
import 'user/user_info.dart';
import 'zhihu/zhihu_main.dart';
import 'package:barcode_scan/barcode_scan.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //底部导航栏数据
  var items = [
    {"name": "新闻", "type": 0, "pic": "images/main_01.jpg"},
    {"name": "段子", "type": 1, "pic": "images/main_02.png"},
    {"name": "音乐", "type": 2, "pic": "images/main_06.jpg"},
    {"name": "视频", "type": 3, "pic": "images/main_07.png"},
    {"name": "小说", "type": 4, "pic": "images/main_04.jpg"},
    {"name": "美图", "type": 5, "pic": "images/main_03.jpg"},
  ];

  NewsIndex _newsIndex;
  int _currentIndex = 0;
  bool hasLogin = false;
  String userHeader = "";
  String userName;
  Constant _constant;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //初始化Bmob
    _newsIndex = NewsIndex();
    _getHeader();
    _getUserName();
    ThemeEvent.getInstance().registerEvent(this);
    _constant=Constant.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child:Scaffold(
          appBar: AppBar(
            title: Text("新闻"),
            actions: <Widget>[
              IconButton(icon: Icon(Icons.crop_free,color: Colors.white,),onPressed: (){
                  _scanner();
              },)
            ],
          ),
          body: IndexedStack(
            children: <Widget>[
              _newsIndex,
            ],
            index: _currentIndex,
          ),
          //侧边栏
          drawer: _drawerView(),
          //底部导航栏
          bottomNavigationBar: BottomNavigationBar(
            items: initBottomItem(),
            onTap: (value) {
              if (value == 0) {
                setState(() {
                  _currentIndex = value;
                });
              } else {
                _itemClick(value);
              }
            },
            type: BottomNavigationBarType
                .fixed, //设置type: BottomNavigationBarType.fixed，否则会当item个数超过3个时，会隐藏底部的文字
          ),
        ),
        onWillPop: _onWillPop);
  }

  //底部导航栏的所有的item列表
  List<BottomNavigationBarItem> initBottomItem() {
    List<BottomNavigationBarItem> bottomitems = [];
    for (var i = 0; i < items.length; i++) {
      bottomitems.add(_bottomItem(i));
    }
    return bottomitems;
  }

  //底部导航栏的单个Item构造方法
  BottomNavigationBarItem _bottomItem(int index) {
    return BottomNavigationBarItem(
      icon: Container(
        width: 25,
        height: 25,
        child: Image.asset(items[index]["pic"]),
      ),
      title: Text(
        items[index]["name"],
        style: TextStyle(
            color:
                _currentIndex == index ? Color(0xffd81e06) : Color(0xffbfbfbf)),
      ),
    );
  }

  //返回键监听
  Future<bool> _onWillPop() {
    _sendBackToHomeMsg();
    return Future.value(false);
  }

  //底部导航栏点击跳转事件
  void _itemClick(int index) {
    switch (index) {
      case 0:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => NewsIndex()));
        break;
      case 1:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => EpisodePager()));
        break;
      case 2:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => Music()))
            .then((va) {
          MusicWindowPlay.getInstance(context).distory();
        });
        break;
      case 3:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => TodayVideoPager()));
        break;
      case 4:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => NovelIndex()));
        break;
      case 5:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => MeiTuPager()));
        break;
    }
  }

  void _sendBackToHomeMsg() async {
    //向 Android 端发送消息，标记跳转到桌面
    var r = await MethodChannel("android_message")
        .invokeMapMethod("back_home", {"action": "go-home"});
  }

  //侧边栏
  Widget _drawerView() {
    return Container(
      width: 260,
      color: Colors.white,
      child: Column(
        children: <Widget>[
          //背景
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            child: Container(
              height: 200,
              alignment: Alignment.bottomCenter,
              padding: EdgeInsets.only(bottom: 25, left: 20, top: 0),
              decoration: BoxDecoration( image: DecorationImage( image: AssetImage(Constant.IMAGE_HEADER_BG), fit: BoxFit.fill),),
              child: Container(
                height: 100,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    //头像
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: userHeader == ""
                                  ? AssetImage(Constant.IMAGE_USER_HANDER)
                                  : NetworkImage(userHeader),
                              fit: BoxFit.fill),
                          borderRadius: BorderRadius.all(Radius.circular(30))),
                    ),
                    Container(
                      height: 60,
                      width: 130,
                      child: Text(
                        hasLogin ? userName : "点击登录",
                        style: TextStyle(color: Colors.white),
                      ),
                      margin: EdgeInsets.only(left: 10, right: 10),
                      alignment: Alignment.topLeft,
                      padding: EdgeInsets.only(top: 10),
                    ),
                    Container(
                      width: 20,
                      alignment: Alignment.center,
                      child: Icon(
                        Icons.navigate_next,
                        color: Colors.white,
                      ),
                    )
                  ],
                ),
              ),
            ),
            onTap: () {
              if (hasLogin) {
                Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) => UserInfo()))
                    .then((info) {
                  _getHeader();
                  if (info == Constant.LOGIN_OUT) {
                    _loginOut();
                  }
                });
              } else {
                Navigator.push(context,
                        MaterialPageRoute(builder: (context) => LoginWidget()))
                    .then((values) {
                  if (values != null && values.toString().isNotEmpty) {
                    setState(() {
                      userName = values[0];
                      hasLogin = true;
                    });
                    _getPic(values[1]);
                  }
                });
              }
            },
          ),
          Expanded(
            child: Container(
              color: _constant.getTheme()?Colors.white:Theme.of(context).primaryColor,
              child: ListView(
                padding: EdgeInsets.only(top: 0),
                children: <Widget>[
                  _drawerItem("知  乎", Constant.IMAGE_ZHIHU, _toZhihu),
                  Container(
                    height: 1,
                    color: Colors.greenAccent,
                  ),
                  _drawerItem(_constant.getTheme()?"夜间模式":"日间模式", _constant.getTheme()?Constant.IMAGE_THEME_DARK:Constant.IMAGE_THEME_DAY, (){
                    ThemeEvent.getInstance().changeTheme();
                  }),
                  Container(
                    height: 1,
                    color: Colors.greenAccent,
                  )
                ],
              ),
            ),
            flex: 1,
          ),
        ],
      ),
    );
  }

  void _toZhihu(){
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (context) => ZhiHu()));
  }

  //侧边栏，头像以下部分的item
  Widget _drawerItem(String name, String image, Function function) {
    return GestureDetector(
      child: Container(
        height: 25,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 20),
        margin: EdgeInsets.only(top: 10, bottom: 10),
        child: Row(
          children: <Widget>[
            Container(
              width: 24,
              height: 24,
              margin: EdgeInsets.only(right: 10),
              child: Image.asset(image),
            ),
            Text(
              name,
              style: TextStyle(fontSize: 18),
            )
          ],
        ),
      ),
      onTap: function,
      behavior: HitTestBehavior.translucent,
    );
  }

  //获取头像
  void _getHeader() async {
    await SharedPrefrenceUtil.getStringValue(Constant.USER_PIC, "").then((header) {
      if (header != "") {
        setState(() {
          userHeader = header;
        });
      }
    });
    _updateHeaderForS();
  }

  //检查头像的更新
  void _updateHeaderForS() async {
    await SharedPrefrenceUtil.getStringValue(Constant.USER_ID, "null").then((user) {
      if (user != "null") {
        _getPic(user);
      }
    });
  }

  //读取用户名
  void _getUserName() async {
    await SharedPrefrenceUtil.getStringValue(Constant.USER_NAME, "null").then((user) {
      if (user != "null") {
        setState(() {
          userName = user;
          hasLogin = true;
        });
      }
    });
  }

  //退出登录
  void _loginOut() {
    setState(() {
      userName = "";
      hasLogin = false;
    });
  }

  //获取头像更新
  void _getPic(String objectId) async {
    BmobQuery<UserInfoBean> query = BmobQuery();
    query.addWhereEqualTo("userId", objectId);
    await query.queryObjects().then((datas) {
      if (datas.length >= 1) {
        UserInfoBean info = UserInfoBean.fromJson(datas[0]);
        SharedPrefrenceUtil.setStringValue(Constant.USER_PIC, info.pic);
        setState(() {
          userHeader = info.pic;
        });
      }
    });
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    ThemeEvent.getInstance().unregister(this);
  }

  void _scanner()async{
    String result=await BarcodeScanner.scan();
    showDialog(context: context,
    builder: (context){
      return Container(
        color: Colors.black12,
        alignment: Alignment.center,
        child: Container(
          width: 240,
          height: 260,
          alignment: Alignment.center,
          child: Column(
            children: <Widget>[
              Container(
                height: 200,
                alignment: Alignment.center,
                child: Text(result,style: TextStyle(decoration: TextDecoration.none,fontSize: 20)),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(8))
                ),
              ),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(top: 25),
                  alignment: Alignment.center,
                  child: Icon(Icons.cancel,color: Colors.white,size: 30,),
                ),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      );
    });

  }

}
